package data

import (
	"MyNotesWeb/bean"
)

// 获取顶级分类
func ListTopSort() (*[]bean.Article, error) {

	if engine, err := GetEngine(); err == nil {
		articles := make([]bean.Article, 0)
		err := engine.Where("cid = 0").Find(&articles)
		if err == nil {
			return &articles, nil
		} else {
			return nil, err
		}
	} else {
		return nil, err
	}

}

// 根据ID获取分类下文章
func GetArticleById(id int64) (*bean.Article, error) {

	if engine, err := GetEngine(); err == nil {
		article := bean.Article{}
		b, err := engine.Id(id).Get(&article)
		if b && err == nil {
			return &article, nil
		} else {
			return nil, err
		}
	} else {
		return nil, err
	}

}

// 获取分类下所有文章
func ListArticle(cid int64) (*[]bean.Article, error) {

	if engine, err := GetEngine(); err == nil {
		articles := make([]bean.Article, 0)
		err := engine.Where("cid = ?", cid).Find(&articles)
		if err == nil {
			return &articles, nil
		} else {
			return nil, err
		}
	} else {
		return nil, err
	}

}

// 插入数据
func SaveArticle(a *bean.Article) (int64, error) {
	if engine, err := GetEngine(); err == nil {
		var n int64
		if a.Id > 0 {
			n, err = engine.Id(a.Id).Update(a)
		} else {
			n, err = engine.Insert(a)
		}

		return n, err

	} else {
		return 0, err
	}
}
